#include "lm_conf_dataserver_wrapper.h"

namespace lm {
	void CALLBACK FuncDataServerOnPingResultCB(
		uint32_t task_id, uint64_t context, int error,
		const LMPingResult* result, void* clientdata) {
		ConfDataServerWrapper* wrapper = reinterpret_cast<ConfDataServerWrapper*>(clientdata);
		wrapper->OnPingResultCB(task_id, context, error, result);
	}

	void ConfDataServerWrapper::OnPingResultCB(uint32_t task_id,
		uint64_t context, int error, const LMPingResult* result) {
		for (ObserverList::iterator it = observer_list_.begin(); it != observer_list_.end(); it++) {
			(*it)->OnPingResult(task_id, context, error, result);
		}
	}

	ConfDataServerWrapper::ConfDataServerWrapper(native_object_t c_object)
		: c_object_(c_object) {
		ConfDataServerCallback cb;
		memset(&cb, 0, sizeof(cb));
		cb.client_data_ = this;
		cb.OnPingResult_ = FuncDataServerOnPingResultCB;
		lm_conf_dataserver_set_callback(c_object_, &cb);
	}

	ConfDataServerWrapper::~ConfDataServerWrapper() {
	}

	void ConfDataServerWrapper::AddObserver(Observer* observer) {
		if (std::find(observer_list_.begin(), observer_list_.end(), observer) == observer_list_.end())
			observer_list_.push_back(observer);
	}

	void ConfDataServerWrapper::RemoveObserver(Observer* observer) {
		ObserverList::iterator it = std::find(observer_list_.begin(), observer_list_.end(), observer);
		if (it != observer_list_.end())
			observer_list_.erase(it);
	}

	int ConfDataServerWrapper::GetDataServerCount() {
		int count = 0;
		lm_conf_dataserver_get_count(c_object_, &count);
		return count;
	}

	int ConfDataServerWrapper::EnumDataServers(LMDataServerInfo* data_Servers, int& count) {
		return lm_conf_dataserver_get_dataserves(c_object_, data_Servers, &count);
	}

	int ConfDataServerWrapper::GetCurrentConnectDataServer(LMDataServerModule module, LMDataServerInfo* data_server) {
		return lm_conf_dataserver_GetCurrentConnectDataServer(c_object_, module, data_server);
	}

	int ConfDataServerWrapper::PingDataServer(const char* address, uint16_t port, int64_t callback_time,
		bool is_use_udp, uint64_t context, uint32_t* task_id) {
		return lm_conf_dataserver_PingDataServer(c_object_, address, port,
                                                 callback_time, is_use_udp ? 1 : 0,
                                                 context, reinterpret_cast<int*>(task_id));
	}

	int ConfDataServerWrapper::StopPingDataServer(uint32_t task_id) {
		return lm_conf_dataserver_StopPingDataServer(c_object_, task_id);
	}

	int ConfDataServerWrapper::SwitchDataServer(LMDataServerModule module, const char* address) {
		return lm_conf_dataserver_SwitchDataServer(c_object_, module, address);
	}

}